#define _CRT_SECURE_NO_WARNINGS
#include "Heap.h"

void HPInit(HP* php) {
	assert(php);
	php->arr = NULL;
	php->size = php->capacity = 0;
}

void HPDestroy(HP* php) {
	assert(php);
	if (php->arr)free(php->arr);
	php->arr = NULL;
	php->size = php->capacity = 0;
}

void HPPrint(HP* php) {
	for (int i = 0; i < php->size; i++)printf("%d ", php->arr[i]);
	printf("\n");
}

void Swap(int* x, int* y) {
	int tmp = *x;
	*x = *y;
	*y = tmp;
}
void AdjustUp(HPDataType* arr, int child) {
	int parent = (child - 1) / 2;
	while (child > 0) {
		if (arr[child] < arr[parent]) {
			Swap(&arr[child], &arr[parent]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else break;
	}
}
void HPPush(HP* php, HPDataType x) {
	assert(php);
	if (php->size == php->capacity) {
		int newCapacity = php->capacity ? 2 * php->capacity : 4;
		HPDataType* tmp = (HPDataType*)realloc(php->arr, newCapacity * sizeof(HPDataType));
		if (tmp == NULL) {
			perror("realloc fail!");
			exit(1);
		}
		php->arr = tmp;
		php->capacity = newCapacity;
	}

	php->arr[php->size] = x;
	AdjustUp(php->arr, php->size);
	++php->size;
}

bool HPEmpty(HP* php) {
	assert(php);
	return php->size == 0;
}

void HPPop(HP* php) {
	assert(!HPEmpty(php));
}